/**
 * Created by li Hong 2017/11/7 0025.
 */
//电站功率预报
$(function () {
    $.ajaxSettings.async = false;
    var table = new tableFactory(1);
    addListeners(table);
});

function tableFactory(pageNum) {
    var me = this;
    me.data = null;
    me.powerForecaset = null;//功率预报配置表
    me.Algorithm = null;//功率算法表
    var init = function () {
        $.when(loadpowerForecast(me)).then(function () {
            $("#powerForecast").bootstrapTable({
                method: 'get',					  //请求方式（*）
                striped: false,					  //是否显示行间隔色
                cache: false,					   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,				   //是否显示分页（*）
                sortable: true,					 //是否启用排序
                sortOrder: "asc",				   //排序方式
                sidePagination: "client",		   //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: pageNum,					   //初始化加载第一页，默认第一页
                search: true,					   //是否显示表格搜索，只能进行客户端搜索
                strictSearch: false,                //true为全匹配，false为模糊查询
                showColumns: true,				  //是否显示筛选列按钮
                showRefresh: false,			  //是否显示刷新按钮
                clickToSelect: true,				//是否启用点击选中行
                showToggle: false,					//是否显示详细视图和列表视图的切换按钮
                cardView: false,					//是否显示详细视图
                detailView: false,				   //是否显示父子表
                singleSelect: true,
                height: 'auto',
                pageSize: 10,
                pageList: [5,10,20],
                columns: [{
                    title: '电站名称', field: 'farmname', align: 'center', valign: 'middle'
                }, {
                    title: '算法列表',
                    field: '',
                    align: '',
                    valign: 'middle',
                    width: '40%',
                    formatter: function (value, row, index) {
                        var id = row['farmid'];
                        var html = [];
                        html.push("<ul>");
                        $.each(me.powerForecaset, function (index, item) {
                            if(id == item.farmid){
                                var fpids = item.fpid;
                                $.each(me.Algorithm, function (index, item) {
                                    if(fpids==item.pfid){
                                        /*<input type ='radio' name='checked'>"+item.pfname+"&nbsp;&nbsp;*/
                                        html.push("<li>"+item.pfname+"</li>");
                                    }
                                });
                            }
                        });
                        html.push("</ul>");
                        return html.join('');
                    }
                }, {
                        title: '最终上传',
                        field: '',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            var id = row['farmid'];
                            var upload;
                            var html = [];
                            $.each(me.powerForecaset, function (index, item) {
                                if(id == item.farmid && item.relation==1){
                                    var fpids = item.fpid;
                                    $.each(me.Algorithm, function (index, item) {
                                        if(fpids==item.pfid){
                                            upload=item.pfname;
                                        }
                                    })
                                }
                            });
                            return upload;
                        }
                },{
                    title: '操作',
                    field: 'caozuo',
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        var html = [];
                        html.push('<button class="btn btn-danger btn-xs" style="margin: 0px 5px;">配置</button>');
                        html.push('<button class="btn btn-success btn-xs" style="margin: 0px 5px;">新增</button>');
                        html.push('<button class="btn btn-info btn-xs" style="margin: 0px 5px;">删除</button>');

                        return html.join('');
                    },
                    events : {
                        'click .btn-danger': function (e, value, row, index) {
                           me.edit(row);
                        },
                         'click .btn-success': function (e, value, row, index) {
                            me.add(row);
                        },
                        'click .btn-info':function (e, value, row, index) {
                            me.delete(row);
                        }
                    }
                }]
            });
            me.loadData();
       });
    };
    init();
}

tableFactory.prototype = {

    loadData: function () {
        var me = this;
        $.when(me.getAlgorithm()).then(function () {
            $.getJSON('../windManage/selectAll', '', function (_data) {
                me.WindData = _data;
                $("#powerForecast").bootstrapTable("load", _data);
            })
        });
    },
    //得到功率算法表数据
    getAlgorithm:function () {
        var me = this;
        $.getJSON('../powerForecast/getAlgorithm', '', function (_data) {
            me.Algorithm = _data;
        })
    },
    edit: function (row) {
        var me = this;
        var id = row['farmid'];
        var html = [];
        html.push('<div style="margin: 10px;><table class="table table-bordered table-normal">');
        html.push('<tr><td>电站名称：</td><td><input type="text" class="form-control" id="farm_name"/></td></tr>');
        html.push('<tr><td>最终上传：</td><td><select type="text" class="form-control" id="last_upload">');
        $.each(me.powerForecaset, function (index, item) {
            if(id == item.farmid){
                var fpids = item.fpid;
                $.each(me.Algorithm, function (index, item) {
                    if(fpids==item.pfid){
                        html.push("<option value='"+item.pfid+"' >"+item.pfname+"</option>");
                    }
                });
            }
        });
        html.push('</select></td></tr>');
        html.push('</table></div>');
        layer.open({
            type: 1,
            title: '设置',
            btn: ['OK'],//可以无限个按钮
            content: html.join(''),
            success: function (layero, index) {
                $("#farm_name").val(row["farmname"]);
            },
            yes:function (index) {
                var id = null;
                var farmid = row["farmid"];
                $.each(me.powerForecaset, function (index, item) {
                    if(farmid == item.farmid&& item.relation == 1){
                        id = item.id;
                    }
                });
                var p = {};
                p.farmid = farmid;
                p.pfid = $("#last_upload").val();
                layer.close(index);
                $.ajax({
                    url : "../powerForecast/lastupload",
                    type : "get",
                    contentType : "application/json",
                    dataType : "json",
                    data :p,//转换成字符串。后台使用了RequestBody注解
                    success : function(data) {
                        if (data === true) {
                            var pageNumber = $('#powerForecast').bootstrapTable('getOptions').pageNumber;
                            $('#powerForecast').bootstrapTable('destroy');
                            new tableFactory(pageNumber);
                            layer.msg("修改成功！", {icon: 1});
                        } else {
                            layer.msg("修改失败！", {icon: 2});
                        }
                    },
                    error :function(){
                        alert("添加失败");
                    }
                });
            }
        });
    },
    add:function(row){
        var me = this;
        var id = row['farmid'];
        var html = [];

        html.push('<div style="margin: 10px;><table class="table table-bordered table-normal">');
        html.push('<tr><td>电站名称：</td><td><input type="text" class="form-control" id="new_farm_name"/></td></tr>');
        html.push('<tr><td>算法列表：</td><td><select type="text" class="form-control" id="new_last_upload">');
        var fpids = new Array();
        $.each(me.powerForecaset, function (index, item) {
            if(id == item.farmid){
                fpids.push( item.fpid);
            }
        });
        $.each(me.Algorithm, function (index, item) {
            if( $.inArray(item.pfid, fpids)===-1){
                html.push("<option value='"+item.pfid+"' >"+item.pfname+"</option>");
            }
        });
        html.push('</select></td></tr>');
        html.push('</table></div>');
        layer.open({
            type: 1,
            title: '设置',
            btn: ['OK'],//可以无限个按钮
            content: html.join(''),
            success: function (layero, index) {
                $("#new_farm_name").val(row["farmname"]);
            },
            yes:function (index) {
                var p = {};
                p.farmid = id;
                p.pfid = $("#new_last_upload").val();
                layer.close(index);
                $.ajax({
                    url : "../powerForecast/insert",
                    type : "get",
                    contentType : "application/json",
                    dataType : "json",
                    data :p,//转换成字符串。后台使用了RequestBody注解
                    success : function(data) {
                        if (data === true) {
                            var pageNumber = $('#powerForecast').bootstrapTable('getOptions').pageNumber;
                            $('#powerForecast').bootstrapTable('destroy');
                            new tableFactory(pageNumber);
                            layer.msg("新增成功！", {icon: 1});
                        } else {
                            layer.msg("新增失败！", {icon: 2});
                        }
                    },
                    error :function(){
                        layer.msg("新增失败！", {icon: 2});
                    }
                });
            }
        });
    },
    delete:function (row) {
        var me = this;
        var id = row['farmid'];
        var html = [];
        html.push('<div style="margin: 10px;><table class="table table-bordered table-normal">');
        html.push('<tr><td>电站名称：</td><td><input type="text" class="form-control" id="farm_name"/></td></tr>');
        html.push('<tr><td>算法列表：</td><td><select type="text" class="form-control" id="last_upload">');
        $.each(me.powerForecaset, function (index, item) {
            if(id == item.farmid){
                var fpids = item.fpid;
                $.each(me.Algorithm, function (index, item) {
                    if(fpids==item.pfid){
                        html.push("<option value='"+item.pfid+"' >"+item.pfname+"</option>");
                    }
                });
            }
        });
        html.push('</select></td></tr>');
        html.push('</table></div>');
        layer.open({
            type: 1,
            title: '设置',
            btn: ['OK'],//可以无限个按钮
            content: html.join(''),
            success: function (layero, index) {
                $("#farm_name").val(row["farmname"]);
            },
            yes:function (index) {
                var id = null;
                var farmid = row["farmid"];
                $.each(me.powerForecaset, function (index, item) {
                    if(farmid == item.farmid&& item.relation == 1){
                        id = item.id;
                    }
                });
                var p = {};
                p.farmid = farmid;
                p.pfid = $("#last_upload").val();
                layer.close(index);
                $.ajax({
                    url : "../powerForecast/delete",
                    type : "get",
                    contentType : "application/json",
                    dataType : "json",
                    data :p,//转换成字符串。后台使用了RequestBody注解
                    success : function(data) {
                        if (data === true) {
                            var pageNumber = $('#powerForecast').bootstrapTable('getOptions').pageNumber;
                            $('#powerForecast').bootstrapTable('destroy');
                            new tableFactory(pageNumber);
                            layer.msg("删除成功！", {icon: 1});
                        } else {
                            layer.msg("删除失败！", {icon: 2});
                        }
                    },
                    error :function(){
                        alert("添加失败");
                    }
                });
            }
        });

    }

};

//获取预报功率配置表数据
function loadpowerForecast (_this) {
    $.getJSON('../powerForecast/selectAll', '', function (_data) {
        _this.powerForecaset = _data;
    });
}

function addListeners (tableObj) {
    $('#btn-add').off('click');
    $('#btn-delete').off('click');
    $('#btn-edit').off('click');
    $('#btn-add').on('click', function () {
        tableObj.save();
    });
    $('#btn-delete').on('click', function () {
        tableObj.delete();
    });
    $('#btn-edit').on('click', function () {
        //tableObj.edit();
    });
}
